package com.cruise.game.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.common.constants.OrderConstants;
import com.cruise.game.common.enums.OrderStatusEnum;
import com.cruise.game.mapper.AgentMapper;
import com.cruise.game.mapper.OrderMapper;
import com.cruise.game.mapper.UserMapper;
import com.cruise.game.model.entity.Agent;
import com.cruise.game.model.entity.Order;
import com.cruise.game.model.entity.User;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.model.vo.order.OrderDetailVO;
import com.cruise.game.model.vo.order.OrderListVO;
import com.cruise.game.service.admin.AdminOrderService;
import com.cruise.game.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员订单服务实现
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class AdminOrderServiceImpl implements AdminOrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AgentMapper agentMapper;

    @Resource
    private OrderService orderService;

    @Override
    public PageResult<OrderListVO> getOrderList(String status, String keyword, LocalDate startDate, LocalDate endDate,
            Integer page, Integer pageSize) {
        // 构建查询条件
        Map<String, Object> params = new HashMap<>();

        // 订单状态
        if (StringUtils.isNotBlank(status) && !"all".equals(status)) {
            params.put("status", status);
        }

        // 搜索关键词（订单号、用户昵称等）
        if (StringUtils.isNotBlank(keyword)) {
            params.put("keyword", keyword);
        }

        // 开始日期和结束日期
        if (startDate != null) {
            params.put("startTime", startDate.atStartOfDay());
        }
        if (endDate != null) {
            params.put("endTime", endDate.atTime(LocalTime.MAX));
        }

        // 分页参数
        params.put("offset", (page - 1) * pageSize);
        params.put("limit", pageSize);

        // 查询订单列表 - 修改为正确处理Map类型的返回值
        List<Map<String, Object>> orderMaps = orderMapper.selectOrderListByParams(params);
        Long total = orderMapper.countOrderListByParams(params);

        // 转换为VO
        List<OrderListVO> orderListVOs = orderMaps.stream()
                .map(this::convertMapToOrderListVO)
                .collect(Collectors.toList());

        return PageResult.of(orderListVOs, total, page, pageSize);
    }

    @Override
    public OrderDetailVO getOrderDetail(Long orderId) {
        // 查询订单详情
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 获取订单详情
        return orderService.getUserOrderDetail(orderId, order.getUserId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignOrder(Long orderId, Long agentId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证订单状态
        if (!OrderConstants.ORDER_STATUS_PENDING.equals(order.getStatus())) {
            throw new ApiException("只能分配待接单状态的订单");
        }

        // 验证代理是否存在
        Agent agent = agentMapper.selectById(agentId);
        if (agent == null) {
            throw new ApiException("代理不存在");
        }

        // 更新订单信息
        order.setAgentId(agentId);
        order.setStatus(OrderConstants.ORDER_STATUS_IN_PROGRESS);
        order.setAcceptedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        return orderMapper.updateById(order) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canCancel(order.getStatus())) {
            throw new ApiException("当前订单状态不可取消");
        }

        // 更新订单状态
        order.setStatus(OrderConstants.ORDER_STATUS_CANCELLED);
        order.setUpdatedAt(LocalDateTime.now());

        // 更新订单
        boolean success = orderMapper.updateById(order) > 0;

        // 退还用户余额
        if (success) {
            userMapper.updateBalance(order.getUserId(), order.getPrice());
        }

        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processAfterSales(Long orderId, Boolean approved, String remark) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证订单状态
        if (!OrderConstants.ORDER_STATUS_AFTER_SALES.equals(order.getStatus())) {
            throw new ApiException("订单不是售后状态");
        }

        // 处理售后
        if (approved) {
            // 同意售后，退款
            order.setStatus(OrderConstants.ORDER_STATUS_CANCELLED);
            userMapper.updateBalance(order.getUserId(), order.getPrice());
        } else {
            // 拒绝售后，恢复完成状态
            order.setStatus(OrderConstants.ORDER_STATUS_COMPLETED);
        }

        // 记录备注（可通过OrderRemark表记录，此处简化处理）

        // 更新订单
        order.setUpdatedAt(LocalDateTime.now());
        return orderMapper.updateById(order) > 0;
    }

    @Override
    public Map<String, Object> getTodayOrderStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(LocalTime.MAX);

        // 今日新增订单数
        int todayNewOrders = orderMapper.countOrdersByTimeRange(todayStart, todayEnd);
        statistics.put("todayNewOrders", todayNewOrders);

        // 今日完成订单数
        int todayCompletedOrders = orderMapper.countCompletedOrdersByTimeRange(todayStart, todayEnd);
        statistics.put("todayCompletedOrders", todayCompletedOrders);

        // 今日订单金额
        BigDecimal todayOrderAmount = orderMapper.sumOrderAmountByTimeRange(todayStart, todayEnd);
        statistics.put("todayOrderAmount", todayOrderAmount != null ? todayOrderAmount : BigDecimal.ZERO);

        // 今日售后订单数
        int todayAfterSalesOrders = orderMapper.countAfterSalesOrdersByTimeRange(todayStart, todayEnd);
        statistics.put("todayAfterSalesOrders", todayAfterSalesOrders);

        return statistics;
    }

    /**
     * 将Map转换为订单列表VO
     */
    private OrderListVO convertMapToOrderListVO(Map<String, Object> orderMap) {
        OrderListVO vo = new OrderListVO();

        // 设置基本属性
        vo.setId(getLongValue(orderMap, "id"));
        vo.setOrderNumber((String) orderMap.get("order_number"));
        vo.setPrice(getBigDecimalValue(orderMap, "price"));
        vo.setStatus((String) orderMap.get("status"));
        vo.setOrderedAt(getDateTimeValue(orderMap, "ordered_at"));
        vo.setAcceptedAt(getDateTimeValue(orderMap, "accepted_at"));
        vo.setCompletedAt(getDateTimeValue(orderMap, "completed_at"));
        vo.setExpectedCompletionTime(getDateTimeValue(orderMap, "expected_completion_time"));

        // 获取服务名称（实际项目中应通过关联查询获取）
        vo.setServiceName("游戏服务");

        return vo;
    }

    /**
     * 从Map中获取Long类型值
     */
    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        return null;
    }

    /**
     * 从Map中获取BigDecimal类型值
     */
    private BigDecimal getBigDecimalValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        } else if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        return null;
    }

    /**
     * 从Map中获取DateTime类型值
     */
    private LocalDateTime getDateTimeValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof LocalDateTime) {
            return (LocalDateTime) value;
        }
        return null;
    }
}